<?php
namespace app\admin\controller;

class ActionLog extends Base{
    //
    protected function initialize() {
        parent::initialize();
        $this->model = 'ActionLog';
        $this->actionArr = ['add' => '新增', 'edit' => '编辑', 'del' => '删除', 'copy' => '复制', 'batch' => '批量', 'none' => '其他'];
    }
    //
    protected function _before_index(){
        $thead = [
            'alid' => 'ID',
            'aid' => '登录账号',
            'model' => '系统模块',
            'action' => '操作类型',
            'value' => '主键ID值',
            'data' => '数据信息',
            'ip' => 'IP地址',
            'agent' => '操作终端',
            'addtime' =>'操作时间',
        ];
        $this->assign('thead', $thead);
        $model = model('Module');
        $oneArr = $model->where('fid', '=', 0)->column('id');
        $moduleArr = $model->where('fid', 'in', $oneArr)->column('id', 'title');
        if($moduleArr){
            foreach($moduleArr as $key => $value){
                $moduleArr[$key] = $model->where('fid', '=', $value)->where('display', '=', 1)->field('title,module')->select()->toArray();
            }
        }
        $this->assign('moduleArr', $moduleArr);
        $this->assign('actionArr', $this->actionArr);
    }
    //
    protected function _filter($map){
        foreach($map as $key => $row){
            if($row[0] == 'model'){
                $map[$key][1] = '=';
                $map[$key][2] = substr($row[2], 1, -1);
            }
        }
        return $map;
    }
    //
    protected function _after_list($list){
        $aidArr = $modelArr = [];
        foreach($list as $row){
            $aidArr[] = $row['aid'];
            $modelArr[] = $row['model'] == 'ReportData' ? 'Report' : $row['model'];
        }
        $adminArr = model('Admin')->where('aid', 'in', $aidArr)->column('username', 'aid');
        $moduleArr = model('Module')->where('module', 'in', $modelArr)->column('title', 'module');
        $moduleArr['ReportData'] = $moduleArr['Report'] ?? '';
        unset($moduleArr['Report']);
        foreach($list as $key => $row){
            $row['model'] = $row['model'] == 'Report' ? 'ReportData' : $row['model'];
            $list[$key]['aid'] = $adminArr[$row['aid']] ?? '';
            $list[$key]['model'] = $moduleArr[$row['model']] ?? '';
            $list[$key]['action'] = $this->actionArr[$row['action']] ?? '';
            $list[$key]['agent'] = agent($row['agent']);
            $list[$key]['data'] = var_export(unserialize($row['data']), true);
            $list[$key]['addtime'] = date('Y-m-d H:i:s', $row['addtime']);
        }
        return $list;
    }
    //
    protected function _filter_del(){
        return [];
    }
    //
    protected function _after_del($rows){
        $logs = [];
        foreach($rows as $row){
            $logs[] = ['pk' => 'alid', 'value' => $row['alid'], 'row' => $row];
        }
        $this->logAll($logs);
    }
}